import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { NzMessageService } from 'ng-zorro-antd/message';
import { PersonnelService } from 'src/app/services/personnel.service';
import { RoleInfo } from 'src/app/models';
import { RoleService } from 'src/app/services/role.service';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { PageTitleService } from 'src/app/services/page-title.service';
@Component({
  selector: 'zepride-details-role',
  templateUrl: './details-role.component.html',
  styleUrls: ['./details-role.component.less']
}) export class DetailsRoleComponent implements OnInit {
  isRersonnelVisible = false;
  id: string;
  PermitssList = [];
  personnellistOfData: []; //人员列表

  RoleInfo: RoleInfo = {} as RoleInfo;
  keyword = ''; //关键字搜索
  usersList = []; //用户人员
  accountRolesList = []; // 添加角色人员 

  constructor(
    private route: Router,
    private msg: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private personnelService: PersonnelService,
    private roleService: RoleService,
    private phSvr: PageTitleService,
  ) {
    //获取编辑需要的参数
    activatedRoute.queryParams.subscribe(queryParams => {
      this.id = queryParams.Id;
    });

  }
  ngOnInit(): void {
    this.getRoleInfoById();
    this.queryAccountPermitss();
  }

  async getRoleInfoById() {
    try {
      const data = await this.roleService.getRoleInfoById(this.id);
      this.RoleInfo = data;

      //人员值转换
      const User = data.users.map(v => {
        return v.name;
      });
      this.usersList = data.users;
      this.RoleInfo.memberUser = User.join("、");
      this.phSvr.setPageHeaderOption({
        title: `${this.RoleInfo.name}详情`,
        subTitle: '用于角色详情查看',
        buttons: [
          {
            text: '添加人员',
            ngType: 'primary',
            icon: "plus-circle",
            onClick: () => {
              this.clickskip();
            }
          },
        ]
      });
    }
    catch (error) {
      ExceptionHandler.current.handleError(error);
    }

  }

  //角色权限
  async queryAccountPermitss() {
    try {
      const data = await this.roleService.queryAccountPermitss({
        authObjectId: this.id, authObjectType: 'Role'
      });
      // 遍历数据格式
      const result = [];

      data.list.forEach((item) => {
        var { groupName } = item;

        if (!result[groupName]) {
          result[groupName] = {
            groupName,
            value: []
          }
        }
        result[groupName].value.push({
          permitId: item.permitId, permitName: item.permitName
        });
      });

      this.PermitssList = Object.values(result);
    }

    catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  //人员列表
  async personnelList() {
    const params = {
      name: this.keyword,
      phone: '',
      employeeNo: '',
      gender: '',
      beginTime: '',
      endTime: '',
      pageIndex: 1,
      countOfPage: 10
    }

    try {
      const data = await this.personnelService.queryUsers(params);

      const list = data.list.map(item => {
        return {
          ...item,
          checked: false
        };
      });

      //判断存在用户人员
      if (this.usersList.length) {
        list.forEach(v => {
          this.usersList.forEach(r => {
            if (v.id == r.id) {
              v.checked = true;

              //加入保存数据
              this.accountRolesList.push({
                accountId: v.accountId,
                roleId: this.id,
              });
            }
          });
        });
      }

      this.personnellistOfData = list;
    }

    catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  clickskip() {
    this.personnelList();
    this.isRersonnelVisible = true;

  }

  confirmInfo() {
    //清空选中值
    this.accountRolesList = [];

    this.personnellistOfData.forEach((v: any) => {
      if (v.checked) {
        this.accountRolesList.push({
          accountId: v.accountId,
          roleId: this.id,
        });
      }
    });
    if (this.accountRolesList.length) {
      this.createAccountRoles();
      this.isRersonnelVisible = false;
    } else {
      if (this.accountRolesList.length == 0) {
        this.msg.create('error', '当前没有角色人员，请先添加角色人员');
        return;
      }
      this.msg.create('error', '请选择角色人员');
      return;
    }
  }

  //添加角色下得用户
  async createAccountRoles() {
    try {
      const data = await this.roleService.createAccountRoles(this.accountRolesList);
      this.msg.success('添加人员成功');
      this.getRoleInfoById();
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  log(value: string[]): void {
    console.log(value);
  }
}